#include <stdio.h>
#include  "list.h"
#include  "cJSON.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

struct modbus_node
{
	int key;
	char name[128];
	int addr;
	int type;
};

struct modbus_node_list
{
	struct modbus_node node;
	struct list_head list;
};

int main(int argc, char const *argv[])
{
	//定义结构体
	struct modbus_node_list head;
	INIT_LIST_HEAD(&head.list);

	struct list_head *pos;
	struct modbus_node_list *tmp;

	//读取点表
	int fd = open("./node.json",O_RDONLY);
	if(fd < 0)
	{
		printf("open error\n");
		return -1;
	}

	char buf[1090];
	ssize_t ret = read(fd,buf,1090);
	if(ret<0)
	{
		printf("read error\n");
		return -1;
	}
	//反序列化
	cJSON *root = NULL;
	cJSON *item = NULL;
	cJSON *array = NULL;
	cJSON *temp = NULL;

	root = cJSON_Parse(buf);
	if(!root)
	{
		printf("Error before:[%s]\n",cJSON_GetErrorPtr());
	}
	else
	{
		item = cJSON_GetObjectItem(root,"modbus");
		printf("%s\n",cJSON_Print(item));
		array = cJSON_GetObjectItem(item,"data");

		//添加链表
		for(int i=0;i<cJSON_GetArraySize(array);i++)
		{
			temp = cJSON_GetArrayItem(array,i);
			struct modbus_node_list *m = (struct modbus_node_list *)malloc(sizeof(struct modbus_node_list));
			m->node.key = atoi(cJSON_Print(cJSON_GetObjectItem(temp,"key")));
			strcpy(m->node.name, cJSON_Print(cJSON_GetObjectItem(temp,"name")));
			m->node.addr = atoi(cJSON_Print(cJSON_GetObjectItem(temp,"addr")));
			m->node.type = atoi(cJSON_Print(cJSON_GetObjectItem(temp,"type")));
			list_add(&m->list,&head.list);
		}

		list_for_each(pos,&head.list)
		{
			tmp = list_entry(pos,struct modbus_node_list,list);
			if(tmp->node.key == 1)
				printf("key = %d name = %s addr = %d type = %d\n",tmp->node.key,tmp->node.name,tmp->node.addr,tmp->node.type);
			else if(tmp->node.key == 2)
				printf("key = %d name = %s addr = %d type = %d\n",tmp->node.key,tmp->node.name,tmp->node.addr,tmp->node.type);
			else if(tmp->node.key == 3)
				printf("key = %d name = %s addr = %d type = %d\n",tmp->node.key,tmp->node.name,tmp->node.addr,tmp->node.type);
			else if(tmp->node.key == 4)
				printf("key = %d name = %s addr = %d type = %d\n",tmp->node.key,tmp->node.name,tmp->node.addr,tmp->node.type);
			else if(tmp->node.key == 5)
				printf("key = %d name = %s addr = %d type = %d\n",tmp->node.key,tmp->node.name,tmp->node.addr,tmp->node.type);
			else if(tmp->node.key == 6)
				printf("key = %d name = %s addr = %d type = %d\n",tmp->node.key,tmp->node.name,tmp->node.addr,tmp->node.type);
			puts("\n");
		}

	}
	return 0;
}
